<template>
  <div class="app-main-container">
    <div class="doumee-filter">
      <el-form inline label-suffix="：" @submit.native.prevent>
        <el-form-item :label="$t('message.sbzt')">
          <el-select
            v-model="filters.status"
            :placeholder="$t('message.qxz') + $t('message.sbzt')"
            clearable
          >
            <el-option
              v-for="item in openStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-preventReClick type="primary" @click="getList(1)">{{
            $t("message.cz")
          }}</el-button>
          <el-button v-preventReClick @click="clear">{{
            $t("message.clear")
          }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-tabs v-model="active" @tab-click="handleClick">
      <el-tab-pane
        v-for="(model, index) in manufacturerList"
        :key="index"
        :label="model.manufacturer"
        :name="index.toString()"
      >
        <div class="doumee-filter manufacturer">
          <div>
            <el-button
              v-if="meta.indexOf('GateAdd') > -1"
              type="primary"
              @click="addDevice"
              >{{ $t("message.add") }}</el-button
            >
            <el-button
              v-if="
                manufacturerList &&
                manufacturerList.length > 0 &&
                manufacturerList[active].id != 11
              "
              type="primary"
              @click="tbBtn(manufacturerList[active].id)"
              >{{ $t("message.tbryzsb") }}</el-button
            >
            <el-button
              v-if="
                manufacturerList &&
                manufacturerList.length > 0 &&
                manufacturerList[active].id == 16 &&
                meta.indexOf('AccountConfig') > -1
              "
              type="primary"
              @click="addDeviceb"
              >{{ $t("message.zhpz") }}</el-button
            >
          </div>
          <div class="detail" @click="manufacturerDetail(model.id)">
            <i class="el-icon-warning-outline" /> {{ $t("message.cssm") }}
          </div>
        </div>
      </el-tab-pane>
      <el-table
        ref="table"
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        :header-row-class-name="'table-header'"
        class="doumee-element-table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          v-if="
            manufacturerList &&
            manufacturerList.length > 0 &&
            manufacturerList[active].id != 11
          "
          key="id"
          align="center"
          type="selection"
          width="55"
        />
        <el-table-column
          key="code"
          align="center"
          :label="$t('message.zjid')"
          prop="code"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          key="name"
          align="center"
          :label="$t('message.zjmc')"
          prop="name"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          key="onlineStatus"
          align="center"
          :label="$t('message.sbzx')"
          prop="onlineStatus"
          min-width="120"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{
              scope.row &&
              (scope.row.onlineStatus == "0" || scope.row.onlineStatus == null)
                ? $t("message.lx2")
                : $t("message.zx2")
            }}</span></template
          >
        </el-table-column>
        <el-table-column
          key="areaName"
          align="center"
          :label="$t('message.glcq')"
          prop="areaName"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="
            manufacturerList &&
            manufacturerList.length > 0 &&
            manufacturerList[active].id == 3
          "
          key="ipAddre"
          align="center"
          :label="$t('message.sbip')"
          prop="ipAddre"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="
            manufacturerList &&
            manufacturerList.length > 0 &&
            manufacturerList[active].id == 3
          "
          key="userAccount"
          align="center"
          :label="$t('message.sbdlyhm')"
          prop="userAccount"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="
            manufacturerList &&
            manufacturerList.length > 0 &&
            manufacturerList[active].id == 3
          "
          key="portCode"
          align="center"
          :label="$t('message.sbdkh')"
          prop="portCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          key="status"
          align="center"
          :label="$t('message.status')"
          min-width="80"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              v-preventReClick
              :active-value="'1'"
              :inactive-value="'0'"
              @change="toConfigUpdate($event, scope.row.id, scope.row.status)"
            />
          </template>
        </el-table-column>
        <el-table-column
          key="operate"
          :label="$t('message.caozuo')"
          align="center"
          min-width="300"
          fixed="right"
        >
          <template slot-scope="scope">
            <div class="flex-cc">
              <el-button
                v-if="
                  manufacturerList[active].functors[0] === '1' &&
                  meta.indexOf('GateEdit') > -1
                "
                v-preventReClick
                type="text"
                @click="toEdit(scope.row)"
                >{{ $t("message.edit") }}</el-button
              >
              <el-button
                v-if="
                  manufacturerList[active].functors[1] === '1' &&
                  meta.indexOf('GateOpenClose') > -1
                "
                v-preventReClick
                type="text"
                @click="controllerSet(scope.row.code, '1')"
                >{{ $t("message.chank") }}</el-button
              >
              <el-button
                v-if="
                  manufacturerList[active].functors[2] === '1' &&
                  meta.indexOf('GateOpenClose') > -1
                "
                v-preventReClick
                type="text"
                @click="controllerSet(scope.row.code, '2')"
                >{{ $t("message.chang") }}</el-button
              >
              <el-button
                v-if="
                  manufacturerList[active].functors[3] === '1' &&
                  meta.indexOf('GateEnable') > -1
                "
                v-preventReClick
                type="text"
                @click="controllerSet(scope.row.code, '4')"
                >{{ $t("message.hf") }}</el-button
              >
              <el-button
                v-if="
                  manufacturerList[active].functors[4] === '1' &&
                  meta.indexOf('GateController') > -1
                "
                v-preventReClick
                type="text"
                @click="controllBtn(scope.row.code, 0)"
                >{{ $t("message.kiamen") }}</el-button
              >
              <el-button
                v-if="
                  manufacturerList[active].functors[5] === '1' &&
                  meta.indexOf('GateController') > -1
                "
                v-preventReClick
                type="text"
                @click="controllBtn(scope.row.code, 1)"
                >{{ $t("message.guanmen") }}</el-button
              >
              <template v-if="manufacturerList[active].functors[5] === '1'">
                <el-button
                  v-if="
                    manufacturerList[active].manufacturer ===
                      $t('message.wgytj') ||
                    manufacturerList[active].manufacturer ===
                      $t('message.wgewm')
                  "
                  v-preventReClick
                  type="text"
                  @click="handleOpenLight(scope.row)"
                  >{{ $t("message.kiamen") }}</el-button
                >
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-tabs>
    <Paginations
      :total="totalCount"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />

    <el-dialog
      :title="newDevice.zhpz ? $t('message.zhpz') : $t('message.zjgl')"
      :visible.sync="dialogTableVisible"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      width="600px"
    >
      <el-form
        ref="newDevice"
        class="doumee-form"
        :model="newDevice"
        label-suffix="："
        :rules="rules"
        label-width="auto"
      >
        <template v-if="newDevice.zhpz">
          <el-form-item :label="$t('message.jgID')" prop="value">
            <el-input
              v-model="newDevice.value"
              class="input-style"
              clearable
              maxlength="50"
              :placeholder="$t('message.qsr') + $t('message.jgID')"
            />
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item :label="$t('message.zjmc')" prop="name">
            <el-input
              v-model="newDevice.name"
              class="input-style"
              clearable
              maxlength="50"
              :placeholder="$t('message.qsr') + $t('message.zjmc')"
            />
          </el-form-item>
          <el-form-item :label="$t('message.sbid')" prop="code">
            <el-input
              v-model="newDevice.code"
              maxlength="50"
              clearable
              class="input-style"
              :placeholder="$t('message.qsr') + $t('message.sbid')"
            />
          </el-form-item>
          <el-form-item :label="$t('message.chanshan')" prop="manufacturerId">
            <el-select
              v-model="newDevice.manufacturerId"
              :placeholder="$t('message.qxz') + $t('message.chanshan')"
              :disabled="
                newDevice.id || newDevice.manufacturerId ? true : false
              "
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in manufacturerList"
                :key="item.id"
                :label="item.manufacturer"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('message.glcq')" prop="areaId">
            <el-select
              v-model="newDevice.areaId"
              :placeholder="$t('message.qxz') + $t('message.glcq')"
              style="width: 100%"
            >
              <el-option
                v-for="item in areaList"
                :key="item.id"
                :label="item.areaName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="
              manufacturerList &&
              manufacturerList.length > 0 &&
              (manufacturerList[active].id == '12' ||
                newDevice.manufacturerId == 3)
            "
            :label="$t('message.sbip')"
            prop="ipAddre"
          >
            <el-input
              v-model="newDevice.ipAddre"
              maxlength="50"
              clearable
              class="input-style"
              :placeholder="$t('message.qsr') + $t('message.sbip')"
            />
          </el-form-item>
          <el-form-item
            v-if="
              manufacturerList &&
              manufacturerList.length > 0 &&
              (manufacturerList[active].id == '12' ||
                newDevice.manufacturerId == 3)
            "
            :label="$t('message.yhm')"
            prop="userAccount"
          >
            <el-input
              v-model="newDevice.userAccount"
              maxlength="50"
              class="input-style"
              clearable
              :placeholder="$t('message.qsr') + $t('message.sbdlyhm')"
            />
          </el-form-item>
          <el-form-item
            v-if="
              manufacturerList &&
              manufacturerList.length > 0 &&
              (manufacturerList[active].id == '12' ||
                newDevice.manufacturerId == 3)
            "
            :label="$t('message.sbmm')"
            prop="userPassword"
          >
            <el-input
              v-model="newDevice.userPassword"
              class="input-style"
              maxlength="50"
              clearable
              type="password"
              :placeholder="$t('message.qsr') + $t('message.sbmm')"
            />
          </el-form-item>
          <el-form-item
            v-if="
              manufacturerList &&
              manufacturerList.length > 0 &&
              (manufacturerList[active].id == '12' ||
                newDevice.manufacturerId == 3)
            "
            :label="$t('message.dkh')"
            prop="portCode"
          >
            <el-input
              v-model="newDevice.portCode"
              class="input-style"
              clearable
              maxlength="50"
              :placeholder="$t('message.qsr') + $t('message.sbdkh')"
            />
          </el-form-item>
          <el-form-item
            v-if="
              newDevice.manufacturerId == 16 ||
              newDevice.manufacturerId == 19 ||
              newDevice.manufacturerId == 20
            "
            :label="$t('message.jccfx')"
            prop="accessType"
          >
            <el-radio-group v-model="newDevice.accessType">
              <el-radio label="1">{{ $t("message.rksb") }}</el-radio>
              <el-radio label="2">{{ $t("message.cksb") }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">{{ $t("message.qx") }}</el-button>
        <el-button
          v-preventReClick
          :loading="subLoading"
          type="primary"
          @click="save"
          >{{ $t("message.qr") }}</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  deviceList,
  accessTypeDetail,
  accessTypeUpdate,
  getAreaList,
  deviceAdd,
  deviceEdit,
  deviceStatusChange,
  deviceController,
  manufacturerList,
  manufacturerDetail,
  syncAllUserToDev,
  equipmentControl,
  weiguangOpenLight,
  bfClick,
} from "@/api";
import { parseTime } from "@/utils";
import store from "@/store";
export default {
  name: "Gate",
  data() {
    return {
      modalDialog: store.getters.dialog,
      subLoading: false,
      meta: [],
      active: "0",
      swiperOptions: {
        slidesPerView: "auto",
        pagination: {
          el: ".swiper-pagination",
        },
      },
      dialogTableVisible: false,
      totalCount: 0,
      list: [],
      listLoading: true,
      openStatus: [
        { value: "1", label: this.$t("message.qy") },
        { value: "0", label: this.$t("message.jy") },
      ],
      deviceStatus: [
        { value: "1", label: this.$t("message.qy") },
        { value: "0", label: this.$t("message.jy") },
      ],
      areaList: [],
      manufacturerList: [],
      filters: {},
      newDevice: { projectIds: [] },
      multipleSelection: [],
      pagination: {
        page: 1,
        rows: 10,
      },
      rules: {
        value: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.jgID"),
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.zjmc"),
            trigger: "blur",
          },
        ],
        code: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.sbId"),
            trigger: "blur",
          },
        ],
        ipAddre: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.sbip"),
            trigger: "blur",
          },
        ],
        userAccount: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.sbdlyhm"),
            trigger: "blur",
          },
        ],
        userPassword: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.sbmm"),
            trigger: "blur",
          },
        ],
        accessType: [
          {
            required: true,
            message: this.$t("message.qxz") + this.$t("message.crcfx"),
            trigger: "change",
          },
        ],
        areaId: [
          {
            required: true,
            message: this.$t("message.qxz") + this.$t("message.glcd"),
            trigger: "change",
          },
        ],
        portCode: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.sbdkh"),
            trigger: "blur",
          },
        ],
        manufacturerId: [
          {
            required: true,
            message: this.$t("message.qxz") + this.$t("message.chanshan"),
            trigger: "change",
          },
        ],
        projectIds: [
          {
            required: true,
            message: this.$t("message.qxz") + this.$t("message.glxm"),
            trigger: "change",
          },
        ],
      },
      manufacturerId: "",
      id: "",
    };
  },
  created() {
    this.meta = this.$route.meta.buttons || [];
    this.listLoading = false;
    this.initData();
  },
  activated() {
    if (this.manufacturerList && this.manufacturerList.length > 0) {
      this.$refs.table.doLayout();
    }
  },
  methods: {
    handleClick(tab, event) {
      const index = parseInt(tab.name);
      const clickedItem = this.manufacturerList[index];
      this.manufacturerId = clickedItem.id;
      this.id = clickedItem.id;
      console.log("Clicked id:", this.manufacturerId);
      this.getList(1);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(value) {
      this.pagination.rows = value;
      this.getList(1);
    },
    toConfigUpdate(e, id, status) {
      deviceStatusChange(
        { param: { id, status } },
        sessionStorage.getItem("venueId")
      )
        .then((res) => {
          if (res.errorCode === "000000") {
            this.$message.success(this.$t("message.czcg"));
            this.getAreaList();
          }
        })
        .catch((err) => {
          console.log(err);
          this.getAreaList();
        });
    },
    tbBtn(manufacturerId) {
      const that = this;
      this.$confirm(this.$t("message.tbryzsbtc"), this.$t("message.ts"), {
        confirmButtonText: this.$t("message.qd"),
        cancelButtonText: this.$t("message.qx"),
        type: "warning",
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== "confirm") {
            close();
            return;
          }
          ctx.confirmButtonLoading = true;
          syncAllUserToDev({
            param: {
              manufacturerId,
              venueId: sessionStorage.getItem("venueId"),
            },
          })
            .then((res) => {
              ctx.confirmButtonLoading = false;
              close();
              if (res.errorCode === "000000") {
                that.$message.success(this.$t("message.tbcg"));
              }
            })
            .catch((err) => {
              ctx.confirmButtonLoading = false;
              close();
              console.log(err);
            })
            .catch(() => {
              ctx.confirmButtonLoading = false;
            });
        },
      }).finally(() => {});
    },
    bfBtn() {
      if (!this.multipleSelection || this.multipleSelection.length === 0) {
        return this.$message(this.$t("message.qxz") + this.$t("message.zhaji"));
      }
      const ids = this.multipleSelection.map((e) => e.id);
      bfClick(
        {
          param: {
            ids: ids.join(),
            venueId: sessionStorage.getItem("venueId"),
            manufacturerId: this.manufacturerList[this.active].id,
          },
        },
        sessionStorage.getItem("venueId")
      )
        .then((res) => {
          if (res.errorCode === "000000") {
            this.$message.success(this.$t("message.yjbfcg"));
            // this.getList(1)
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleOpenLight(row) {
      const that = this;
      this.$confirm(this.$t("message.kdtc"), this.$t("message.ts"), {
        confirmButtonText: this.$t("message.qd"),
        cancelButtonText: this.$t("message.qx"),
        type: "warning",
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== "confirm") {
            close();
            return;
          }
          ctx.confirmButtonLoading = true;
          weiguangOpenLight({
            param: {
              deviceSn: row.code,
              manufacturerId: row.manufacturerId,
            },
          })
            .then((res) => {
              ctx.confirmButtonLoading = false;
              close();
              if (res.errorCode === "000000") {
                that.$message.success(this.$t("message.kdcg"));
                that.getList();
              }
            })
            .catch(() => {
              ctx.confirmButtonLoading = false;
            });
        },
      }).finally(() => {});
    },
    controllBtn(id, type) {
      const that = this;
      let str = this.$t("message.kiamen");
      if (type === 1) {
        str = this.$t("message.guanmen");
      }
      this.$confirm(
        this.$t("message.cczj") + str + this.$t("message.sfjxtc"),
        this.$t("message.ts"),
        {
          confirmButtonText: this.$t("message.qd"),
          cancelButtonText: this.$t("message.qx"),
          type: "warning",
          callback: () => {},
          beforeClose: (action, ctx, close) => {
            if (action !== "confirm") {
              close();
              return;
            }
            ctx.confirmButtonLoading = true;
            equipmentControl({
              param: {
                id,
                type,
                manufacturerId: that.manufacturerList[that.active].id,
                shopId: localStorage.getItem("shopId"),
              },
            })
              .then((res) => {
                ctx.confirmButtonLoading = false;
                close();
                if (res.errorCode === "000000") {
                  if (type === 0) {
                    that.$message.success(this.$t("message.kmcg"));
                  } else {
                    that.$message.success(this.$t("message.gmcg"));
                  }
                }
              })
              .catch(() => {
                ctx.confirmButtonLoading = false;
              });
          },
        }
      ).finally(() => {});
    },
    addDevice() {
      let manufacturerId = this.manufacturerId;
      this.newDevice = {};
      this.newDevice.manufacturerId = manufacturerId;
      this.dialogTableVisible = true;
    },
    addDeviceb() {
      accessTypeDetail({ param: { type: 19 } }).then((res) => {
        if (res.errorCode === "000000") {
          if (res.recordList.length > 0) {
            this.newDevice = {
              ...res.recordList[0],
              zhpz: "1",
            };
          } else {
            this.newDevice = {
              zhpz: "1",
            };
          }
          this.dialogTableVisible = true;
        }
      });
    },
    toEdit(item) {
      this.dialogTableVisible = true;
      this.newDevice = { ...item };
      this.newDevice.manufacturerId = parseInt(item.manufacturerId);
    },
    controllerSet(deskId, flag) {
      deviceController({ param: { deskId, flag } }).then((res) => {
        if (res.errorCode === "000000") {
          this.$message.success(this.$t("message.qhcg"));
        } else {
          this.$message.error(this.$t("message.qhsb"));
        }
      });
    },
    initData() {
      this.getArea();
      manufacturerList({ param: { type: 0 } })
        .then((res) => {
          if (res.errorCode === "000000") {
            this.manufacturerList = res.recordList;
            this.manufacturerId = res.recordList[0].id;
            this.getList(1);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getList(page) {
      const { filters, pagination } = this;
      const venueId = sessionStorage.getItem("venueId");
      if (page) {
        pagination.page = page;
        this.pagination.page = page;
      }
      pagination.firstQueryTime = parseTime(new Date());
      this.listLoading = true;
      deviceList(
        {
          pagination,
          gymId: sessionStorage.getItem("venueId"),
          param: {
            venueId,
            manufacturerId: this.manufacturerList[this.active].id,
            ...filters,
          },
        },
        sessionStorage.getItem("venueId")
      )
        .then((res) => {
          this.listLoading = false;
          if (res.errorCode === "000000") {
            this.list = res.recordList;
            this.totalCount = res.totalCount;
          }
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    getArea() {
      getAreaList({
        param: { venueId: sessionStorage.getItem("venueId") },
      }).then((res) => {
        if (res.errorCode === "000000") {
          this.areaList = res.recordList;
        }
      });
    },
    clear() {
      this.filters = {};
      this.getList(1);
    },
    cancel() {
      this.dialogTableVisible = false;
    },
    save() {
      console.log(this.newDevice);
      this.$refs.newDevice.validate((valid) => {
        if (valid) {
          const param = { ...this.newDevice };
          param.venueId = sessionStorage.getItem("venueId");
          this.subLoading = true;
          if (param.zhpz) {
            accessTypeUpdate({ param }, sessionStorage.getItem("venueId"))
              .then((res) => {
                this.subLoading = false;
                if (res.errorCode === "000000") {
                  this.$message.success(this.$t("message.pzcg"));
                  this.getList(1);
                  this.dialogTableVisible = false;
                }
              })
              .catch((err) => {
                this.subLoading = false;
                console.log(err);
              });
          } else if (this.newDevice.id) {
            param.id = this.newDevice.id;
            deviceEdit({ param }, sessionStorage.getItem("venueId"))
              .then((res) => {
                this.subLoading = false;
                if (res.errorCode === "000000") {
                  this.$message.success(this.$t("message.editcg"));
                  this.getList(1);
                  this.dialogTableVisible = false;
                }
              })
              .catch((err) => {
                this.subLoading = false;
                console.log(err);
              });
          } else {
            deviceAdd({ param }, sessionStorage.getItem("venueId"))
              .then((res) => {
                this.subLoading = false;
                if (res.errorCode === "000000") {
                  this.$message.success(this.$t("message.addcg"));
                  this.getList(1);
                  this.dialogTableVisible = false;
                }
              })
              .catch((err) => {
                this.subLoading = false;
                console.log(err);
              });
          }
        } else {
          // this.$alert(this.$t('message.qxwssbxx'), this.$t('message.cw'))
        }
      });
    },
    manufacturerDetail(id) {
      manufacturerDetail(
        { param: { manufacturerId: this.manufacturerList[this.active].id } },
        sessionStorage.getItem("venueId")
      )
        .then((res) => {
          console.log(res);
          if (res.errorCode === "000000") {
            const cont =
              res.record.manufacturer + res.record.text.replace(/\n/g, "<br/>");
            this.$alert(cont, this.$t("message.cssm"), {
              dangerouslyUseHTMLString: true,
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>
